<template>
	<view class="content">
		<text class="text">{{ tiptext }}</text>
		<p v-if="powerStatus">
			未授权，当前授权端口为：
			<text style="color: #ff0000">{{ udpport }}</text>
		</p>
	</view>
</template>

<script>
import API from '@/utils/api.js';
import DB from '@/utils/sqldb.js';
import defaData from '@/utils/defaData.json';
import imageData from '@/utils/images.json';

const udpClient = uni.requireNativePlugin('udp-client');
export default {
	data() {
		return {
			tiptext: '初始化中...',
			powerStatus: false
		};
	},
	computed: {
		udpport() {
			// 1000到65535之间的任意一个未被使用的端口
			return 1000 + Math.floor(Math.random() * 65535);
		}
	},
	methods: {
		// 创建菜单数据
		creatDefaType() {
			let arr = [];
			for (let i = 0; i < defaData.typeData.length; i++) {
				arr.push(API.recordSalary(defaData.typeData[i]));
			}
			for (let i = 0; i < defaData.songData.length; i++) {
				arr.push(API.recordSong(defaData.songData[i]));
			}
			for (let i = 0; i < imageData.length; i++) {
				arr.push(
					API.recordImage({
						id: imageData[i].id,
						url: '',
						father_id: imageData[i].father_id
					})
				);
			}
			arr.push(
				API.recordPower({
					id: 1,
					code: 'false'
				})
			);
			Promise.all(arr).then(
				(res) => {
					console.log('添加默认菜单数据', res);
					this.tiptext = '初始化完成';
					this.handleTabbar();
				},
				(err) => {
					console.log('菜单添加失败', err);
				}
			);
		},

		handleTabbar() {
			if (!this.powerStatus && this.tiptext == '初始化完成') {
				this.closeudp();
				uni.switchTab({
					url: '/pages/index/index'
				});
			}
		},

		onSocketMsg(resData) {
			// resData 的数据结构：{ host, port, data, hex }
			console.log('接收到消息: ' + JSON.stringify(resData), resData.data);
			API.recordPower({
				id: 1,
				code: 'true'
			}).then((res) => {
				console.log('授权成功', res);
				uni.showToast({
					icon: 'success',
					title: '授权成功',
					duration: 2000
				});
				this.powerStatus = false;
				this.handleTabbar();
			});
		},
		onSocketError(errMsg) {
			console.error('socket 异常：' + errMsg);
		},
		closeudp() {
			// 释放 socket，释放端口
			udpClient.release();
		},

		getjson() {
			// fetch('@/utils/images.json')
			// 	.then((res) => res.json())
			// 	.then((res) => {
			// 		console.log('下载的数据', res);
			// 	})
			// 	.catch((err) => {
			// 		console.error(err);
			// 	});
			// var xhr = new XMLHttpRequest();
			// xhr.overrideMimeType('application/json');
			// xhr.open('GET', '@/utils/images.json', true);
			// xhr.onreadystatechange = function () {
			// 	console.log('下载的数据', JSON.parse(xhr.responseText));
			// };
			// $.getJSON('../../utils/images.json', (data) => {
			// 	console.log(data.length, '下载的数据');
			// }).fail(() => {
			// 	console.log('报错');
			// });
		}
	},
	onLoad() {
		udpClient.setIsDebug(true);
		udpClient.setUseHex(false);
		udpClient.setByteSize(2048);
		udpClient.init(this.udpport, this.onSocketMsg, this.onSocketError);
	},
	onUnload() {
		this.closeudp();
	},
	async onShow() {
		this.getjson();
		console.log('默认数据', defaData.typeData);
		// #ifdef APP-PLUS
		let res = await DB.queryTable(DB.recordsTable);
		let res1 = await DB.queryTable(DB.songsTable);
		let res3 = await DB.queryTable(DB.imagesTable);
		let res2 = await DB.queryTable(DB.powerTable);

		console.log(res, res1, '查询结果');
		if (!res) {
			const table1 = await DB.createTable(DB.recordsTable, 'id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,father_id INTEGER, user TEXT');
			console.log(table1, '创建菜单表格');
			const table2 = await DB.createTable(
				DB.songsTable,
				'id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,urls LONGTEXT,type TEXT,author TEXT,album TEXT,father_id INTEGER,user INTEGER'
			);
			console.log(table2, '创建乐谱表格');
			const table3 = await DB.createTable(DB.powerTable, 'id INTEGER PRIMARY KEY AUTOINCREMENT,code TEXT');
			console.log(table3, '创建权限表格');
			const table4 = await DB.createTable(DB.imagesTable, 'id INTEGER PRIMARY KEY AUTOINCREMENT,url TEXT,father_id INTEGER');
			console.log(table4, '创建图片表格');
			let promes = [];
			for (let i = 0; i < imageData.length; i++) {
				promes.push(API.createFlie(imageData[i], `${imageData[i].father_id}${imageData[i].id}`));
			}
			let adddata = await Promise.all(promes);
			console.log('添加的文件', adddata);
		} else {
			this.tiptext = '初始化完成';
		}

		let res2data = await API.getAllPower();
		console.log('查询的权限数据', res2data);
		if (!res2data.length) {
			this.powerStatus = true;
		} else {
			if (res2data[0].code == 'false') {
				this.powerStatus = true;
			} else {
				this.powerStatus = false;
			}
		}

		if (!res && !res1) {
			this.creatDefaType();
		} else {
			if (this.powerStatus) {
			} else {
				this.closeudp();
				uni.switchTab({
					url: '/pages/index/index'
				});
			}
		}
		// #endif
	}
};
</script>

<style lang="scss" scoped>
.content {
	width: 100vw;
	height: 100vh;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;

	.text {
		display: block;
		margin: 10rpx;
	}
}
</style>
